import {
    getClientReqCount,
    getServerRespCount,
    getReqLatency,
    getPodTgidByTcpMetric,
    getRespLatency,
    getServerErrRate,
    getTop3ReqRate,
    getTop3ServerErrRate,
    getTop3RespLatency,
    getAppTcpLinkCount,
    getAppTcpLinkSrtt,
    getAppTcpLinkCountByClientServer,
    getAppTcpLinkSrttByClientServer,
    getL7ObjectList
} from '@/api';

const noData = '-';

export { noData }

export async function getReqRate(node) {
  var result = noData;
  const [_, res] = await getClientReqCount(node)
  var data = res.data.result;
  if (data.length !== 0) {
    var value = Number(data[0].value[1]);
    if (value !== 0) {
      result = `${(value / 300).toFixed(2)} req/s`;
    }
  }
  return result;
}

export async function getRespRate(node) {
  var result = noData;
  const [_, res] = await getServerRespCount(node)
  var data = res.data.result;
  if (data.length !== 0) {
    var value = Number(data[0].value[1]);
    if (value !== 0) {
      result = `${(value / 300).toFixed(2)} resp/s`;
    }
  }
  return result;
}

export async function getServerExceptionRate(node) {
  var result = noData;
  const [_, res] = await getServerErrRate(node)
  var data = res.data.result;
  if (data.length !== 0) {
    result = `${Number(data[0].value[1]).toFixed(2) * 100}%`;
  }
  return result;
}

export async function getServerRespLatency(node) {
  var result = noData;
  var temp;
  const [_, res] = await getRespLatency(node)
  var data = res.data.result;
  if (data.length !== 0) {
    temp = (Number(data[0].value[1]) / 1000).toFixed(2);
    result = `${(temp / 1000).toFixed(2)} ms`;
  }
  return result;
}

export async function getClientReqLatency(node) {
  var result = noData;
  var temp;
  const [_, res] = await getReqLatency(node)
  var data = res.data.result;
  if (data.length !== 0) {
    temp = (Number(data[0].value[1]) / 1000).toFixed(2);
    result = `${(temp / 1000).toFixed(2)} ms`;
  }
  return result;
}

export async function getPodTgidByTcpMetrics(param) {
  var machineId, tgid, data;
  const [_, res] = await getPodTgidByTcpMetric(param)
  data = res.data.result;
  if (data.length !== 0) {
    machineId = data[0].metric.machine_id.substr(0, 36);
    tgid = data[0].metric.tgid;
  }
  return {machine_id: machineId, tgid: tgid};
}

function getObjectInfo(item) {
    if (!('container_id' in item) && !('pod_id' in item)) {
        return { type: 'proc', objectId: item.tgid, machine_id: item.machine_id, name: `${item.job}_${item.comm}_${item.tgid}` };
    } else if (!('pod_id' in item)) {
        return { type: 'container', objectId: item.container_id, machine_id: item.machine_id, name: `${item.job}_${item.container_name}` };
    } else {
        return { type: 'pod', objectId: item.pod_id, machine_id: item.machine_id, name: `${item.job}_${item.pod}` };
    }
}

export async function getTopReqRateObjectList(param) {
  const result = []
  const [_, res] = await getTop3ReqRate(param)
  const data = res.data.result
  if (data.length !== 0) {
    for (var item of data) {
      result.push(getObjectInfo(item.metric))
    }
  }
  return result
}

export async function getTopServerErrRateObjectList(node) {
  var result = []
  const [_, res] = await getTop3ServerErrRate(node)
  var data = res.data.result
  if (data.length !== 0) {
    for (var item of data) {
      result.push(getObjectInfo(item.metric))
    }
  }
  return result
}

export async function getTopRespLatencyObjectList(node) {
  var result = [];
  const [_, res] = await getTop3RespLatency(node)
  var data = res.data.result;
  if (data.length !== 0) {
    for (var item of data) {
      result.push(getObjectInfo(item.metric));
    }
  }
  return result;
}

export async function getAppTcpLinkSrttAvg(param) {
  var data;
  var tcplinkCount = 0;
  var tcplinkSum = 0;
  const res1 = await getAppTcpLinkCount(param)
  data = res1[1].data.result;
  if (data.length !== 0) {
    tcplinkCount = data.length;
  }

  if (tcplinkCount === 0) {
    return '-';
  }
  const res2 = await getAppTcpLinkSrtt(param)
  data = res2[1].data.result;
  if (data.length !== 0) {
    for (var item of data) {
      tcplinkSum += (Number(item.metric.le) * Number(item.value[1]));
    }
  } else {
    return '-';
  }

    console.log(param.name, ' sum ', tcplinkSum, ' / ', tcplinkCount);

    return `${Number(tcplinkSum / tcplinkCount / 1000).toFixed(2)} ms`
}

export async function getAppTcpLinkSrttAvgByClientServer(client, server) {
  var data;
  var tcplinkCount = 0;
  var tcplinkSum = 0;
  const res1 = await getAppTcpLinkCountByClientServer(client, server)
  data = res1[1].data.result;
  if (data.length !== 0) {
    tcplinkCount = data.length;
  }

  if (tcplinkCount === 0) {
    return '-';
  }

  const res2 = await getAppTcpLinkSrttByClientServer(client, server)
  data = res2[1].data.result;
  if (data.length !== 0) {
    for (var item of data) {
      tcplinkSum += (Number(item.metric.le) * Number(item.value[1]));
    }
  } else {
    return '-';
  }

  return `${Number(tcplinkSum / tcplinkCount / 1000).toFixed(2)} ms`
}

export async function getCSTrafficList(param) {
  var tableData = [];
  var queryKeyword = param.queryKeyword;

  // sum(gala_gopher_l7_resp_count)by(tgid, container_id, pod_id, l7_role)
  // 根据 进程、容器、pod、l7角色 汇总
  // 1.获取 客户端列表，  获取客户端的 请求速率， 请求时延
  // 2.获取对应的服务端列表
  //  根据 客户端的 l7 server_ip 和 server_port 获取 server 数据
  // 获取 服务端的 应答速率 服务端异常比例  响应时延
  const [_, res] = await getL7ObjectList(param)
  console.log('getL7ObjectList', res);
  const data = res.data.result;
  var key, objectId, type, name, item;
  var clientMap = new Map();
  var serverMap = new Map();
  var findServer = false;
  var tempTableData = [];
  var id = 0;

  for (const i of data) {
    const item = i.metric;
    if ('pod_id' in item) {
      type = 'pod';
      objectId = item.pod_id;
      name = item.pod;
    } else if ('container_id' in item) {
      type = 'container';
      objectId = item.container_id;
      name = item.container_name;
    } else if ('tgid' in item) {
      type = 'proc';
      objectId = item.tgid;
      name = `${item.comm}_${item.tgid}`;
    }
    key = `${item.machine_id}_${objectId}`;
    item.timestamp = param.endTime * 1000;
    if (item.l7_role === 'client' && !clientMap.has(key)) {
      const client = item;
      client.type = type;
      client.objectId = objectId;
      client.name = name;
      client.reqRate = await getReqRate(client);
      client.reqLatency = await getClientReqLatency(client);
      clientMap.set(key, client);
    }

    if (item.l7_role === 'server' && !serverMap.has(key)) {
      const server = item;
      server.type = type;
      server.objectId = objectId;
      server.name = name;
      server.respRate = await getRespRate(server);
      server.respLatency = await getServerRespLatency(server);
      server.serverExceptionRate = await getServerExceptionRate(server);
      serverMap.set(key, server);
    }
  }

  for (const i of data) {
    const item = i.metric;
    if ('pod_id' in item) {
      type = 'pod';
      objectId = item.pod_id;
    } else if ('container_id' in item) {
      type = 'container';
      objectId = item.container_id;
    } else if ('tgid' in item && 'comm' in item) {
      type = 'proc';
      objectId = item.tgid;
    } else {
      continue;
    }
    key = `${item.machine_id}_${objectId}`;

    if (item.l7_role === 'client') {
      findServer = false;
      for (var value of serverMap.values()) {
        if (value.server_ip === item.server_ip && value.server_port === item.server_port) {
          const client = clientMap.get(key)
          tempTableData.push({
            client: client,
            clientReqRate: client.reqRate,
            serverExceptionRate: value.serverExceptionRate,
            clientReqLatency: client.reqLatency,
            serverRespLatency: value.respLatency,
            server: value,
            id: id++,
            tcpLatency: await getAppTcpLinkSrttAvgByClientServer(clientMap.get(key), value)
          });
          findServer = true;
          break;
        }
      }
      if (findServer === false) {
        tempTableData.push({
          client: clientMap.get(key),
          server: {
            type: 'ip',
            name: `${item.server_ip}:${item.server_port}`,
            respRate: '-',
            respLatency: '-',
            serverExceptionRate: '-'
          },
          id: id++,
          tcpLatency: await getAppTcpLinkSrttAvgByClientServer(clientMap.get(key), {
            server_ip: item.server_ip,
            server_port: item.server_port
          })
        });
      }
    }
  }

  if (queryKeyword === '') {
    tableData = tempTableData;
    return tableData;
  }

  for (item of tempTableData) {
    if (
      ('tgid' in item.client && item.client.tgid.indexOf(queryKeyword) !== -1) ||
      ('tgid' in item.server && item.server.tgid.indexOf(queryKeyword) !== -1) ||
      ('container_name' in item.client && item.client.container_name.indexOf(queryKeyword) !== -1) ||
      ('container_name' in item.server && item.server.container_name.indexOf(queryKeyword) !== -1) ||
      ('pod' in item.client && item.client.pod.indexOf(queryKeyword) !== -1) ||
      ('pod' in item.server && item.server.pod.indexOf(queryKeyword) !== -1)
    ) {
      tableData.push(item)
    }
  }


    return tableData;
}
